<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
//json_encode($data,\JSON_HEX_TAG); 用于使html 标签不丢失的转义

// 应用公共文件
use phpmailer\phpmailer;


/**
 * 下划线转驼峰
 * 思路:
 * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
 * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
 */
function camelize($uncamelized_words,$separator='_')
{
    $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}

/**
 * 驼峰命名转下划线命名
 * 思路:
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
function uncamelize($camelCaps,$separator='_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}



//多维数组去重
function assoc_unique($arr, $key)
{
    $tmp_arr = array();
    foreach($arr as $k => $v)
    {
        if(in_array($v[$key], $tmp_arr))//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
        { // www.jbxue.com
            unset($arr[$k]);
        }
        else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}
/**
 * 数组转xml字符串 闭合
 * @param array $arr 数组
 * @param string $root 外层标签
 * @param xml  返回xml字符串
 */
function arrToXml($arr,$root="root",$dom=0,$item=0){
    if (!$dom){
        $dom = new DOMDocument("1.0");
    }
    if(!$item){
        $item = $dom->createElement($root);
        $dom->appendChild($item);
    }
    foreach ($arr as $key=>$val){
        $itemx = $dom->createElement(is_string($key)?$key:"item");
        $item->appendChild($itemx);
        if (!is_array($val)){
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);
        }else {
            arrToXml($val,$root="",$dom,$itemx);
        }
    }
    return $dom->saveXML();
}

// 定义一个函数getIP()
function getIP()
{
    global $ip;
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    return $ip;
}

/**
 * 将xml字符串转换为数组
 * @param string $contents  带转换的xml格式数据
 * @param string $encoding  编码
 * @param int $get_attrbutes
 * @param string  优先级
 * @param array  返回数组
 */
function xmlToArr($contents = NULL,$get_attributes = 1, $priority = 'tag',$encoding = 'UTF-8') {

    if(!$contents) {
        return array();
    }
    if(!function_exists('xml_parser_create')) {
        return array();
    }
    //xml解析器
    $parser = xml_parser_create('');
    xml_parser_set_option($parser,XML_OPTION_TARGET_ENCODING,$encoding);
    //将标签原样输出，不转换成大写
    xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
    //是否忽略空白字符
    xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
    //$xml_values,$index引用类型，将文本解析到指定的数组变量中
    xml_parse_into_struct($parser, trim($contents), $xml_values/*,$index*/);
    //释放解析器

    xml_parser_free($parser);
    if(!$xml_values)
        return '';
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();
    //当前操作结构的指针
    $current = & $xml_array;
    //同级结构下重复标签的计数
    $repeated_tag_index = array();
    foreach ($xml_values as $data) {
        //删除属性和值，确保每次用到的是新的
        unset($attributes, $value);
        //将标签结构数组，释放到当前的变量域中
        extract($data);
        //存当前标签的结果
        $result = array();
        //存属性
        $attributes_data = array();
        //标签有value
        if(isset($value)) {
            if($priority == 'tag'){
                $result = trim($value);
            }else{
                $result['value'] = trim($value);
            }
        }
//        dump($result);
        //标签有属性，且不忽略
        if($get_attributes && isset($attributes)) {
            foreach ($attributes as $attr => $val) {
                if ($priority == 'tag'){//放入单独记录属性的数组中
                    $attributes_data[$attr] = $val;
                }else{//统一放入$result中
                    $result['attr'][$attr] = $val;
                }
            }
        }
        //处理节点关系
        if ($type == "open") {//有子节点标签
            $parent[$level - 1] = & $current; //$parent[$level - 1],指向复合标签的起始处
            if (!is_array($current) || (!in_array($tag, array_keys($current)))) {//xml复合标签的第一个
                $current[$tag] = $result;//属性独立
                /*处理结果
                    [tag] => Array
                    (
                        [value] => aaaa,
                        [attr] => Array
                            (
                                [a] => xxx
                            )
                    )
                */
                if ($attributes_data){
                    $current[$tag . '_attr'] = $attributes_data;
                    /*处理结果
                        [tag] => xxxx,
                        [tag_attr] => Array
                            (
                                [a] => xxx
                            )
                    */
                }
                $repeated_tag_index[$tag . '_' . $level] = 1;//记录同级中该标签重复的个数
                //指针重新指向符合标签的子标签
                $current = & $current[$tag];
            }else {
                if (isset($current[$tag][0])) {//第3+个同级复合标签
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level] ++;
                } else {//第2个同级复合标签
                    //在关联数组外包一层索引数组
                    $current[$tag] = array(
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    //此处只记录第一个重复标签的属性，可能有bug，需注意！
                    //要想区别各子标签的属性，需要将$priority设成非'tag'
                    if (isset($current[$tag . '_attr'])) {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset($current[$tag . '_attr']);
                    }
                }
                //记录最后一个重复子标签的索引
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                //指针指向下一个子标签
                $current = & $current[$tag][$last_item_index];
            }
        } elseif ($type == "complete") {
            //第一个complete类型的标签
            if($result==[]){
                if(empty($result)){
                    $result = '';
                }
            }
            if (!isset($current[$tag])) {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' && $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else {
                //第3+个同级子标签
                //此处只有$current[$tag][0]，不行，因为可能索引到字符串的第一个字符
                if(isset($current[$tag][0]) && !is_array($current[$tag])){
                    print_r($current);exit();
                }
                if(isset($current[$tag][0]) && is_array($current[$tag])) {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    //子标签的属性不忽略
                    if ($get_attributes &&  $priority == 'tag' && $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level] ++;
                }else{//第2个同级子标签
                    $current[$tag] = array(
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' && $get_attributes) {
                        if (isset($current[$tag . '_attr'])) {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset($current[$tag . '_attr']);
                        }
                        if ($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level] ++;
                }
            }
        }elseif($type == 'close'){
            //闭合标签和起始标签level相同，因此进入complete类型的子标签后，可以通过父节点的close标签，可以指回到父节点
            $current = & $parent[$level - 1];
        }
    }
    return $xml_array;
}
/**
 * 转义字符串中html标签,如果参数为数组则遍历
 *
 * @param mixed $string 待转换的字符
 * @return mixed
 */
function htmlspecialchars_deep($string)
{
    return is_array($string) ? array_map('htmlspecialchars_deep', $string) : htmlspecialchars($string, ENT_QUOTES);
}
/**
 * 使用反斜线引用字符串,如果参数为数组则遍历
 *
 * @param mixed $string 待转换的字符
 * @return mixed
 */
function addslashes_deep($string)
{
    return is_array($string) ? array_map('addslashes_deep', $string) : addslashes($string);
}
/**
 * 使用反斜线引用字符串,如果参数为数组则深度遍历
 *
 * @param mixed $string 待转换的字符
 * @return mixed
 */
function new_addslashes($string)
{
    if(!is_array($string)) return addslashes($string);
    foreach($string as $key => $val) $string[$key] = new_addslashes($val);
    return $string;
}

/**
 * 使用反斜线引用字符串
 *
 * @param mixed $string 待转换的对象
 * @return mixed
 */
function addslashes_deep_obj($obj)
{
    if (is_object($obj))
    {
        foreach ($obj as $key => $val)
        {
            $obj->$key = addslashes_deep($val);
        }
    }
    else
    {
        $obj = addslashes_deep($obj);
    }
    return $obj;
}

/**
 * 去掉字符串中的反斜线
 *
 * @param mixed $string 待转换的字符
 * @return mixed
 */
function stripslashes_deep($string)
{
    return is_array($string) ? array_map('stripslashes_deep', $string) : stripslashes($string);
}

/**
 * 清除js数据中的换行与反斜线
 *
 * @param string $string 待转换的字符
 * @return string
 */
function js_format($string)
{
    return addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
}

/**
 * 将html转换成text
 *
 * @param string $string 待转换的字符
 * @return string
 */
function text_format($string)
{
    return nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($string)));
}

/**
 * 格式化ID
 *
 * @param mixed $id
 * @return int
 */
function id_format($id)
{
    if (is_numeric($id)) return $id;
    if (is_array($id)) return array_filter($id, 'is_numeric');
    if (strpos($id, ',') !== false) return preg_match("/^([\d]+,)+$/", $id.',') ? explode(',', $id) : false;
    return false;
}

/**
 * 编码转换
 *
 * @param	string	$_in_charset	输入字符集
 * @param	string	$_out_charset	输出字符集
 * @param	mixed	$str_or_ary		内容
 * @return	mixed
 */

function str_charset($in_charset, $out_charset, $str_or_arr)
{
    $lang = array(&$in_charset, &$out_charset);
    foreach ($lang as &$l)
    {
        switch (strtolower(substr($l, 0, 2)))
        {
            case 'gb': $l = 'gbk';
                break;
            case 'bi': $l = 'big5';
                break;
            case 'ut': $l = 'utf-8';
                break;
        }
    }

    if(is_array($str_or_arr))
    {
        foreach($str_or_arr as &$v)
        {
            $v = str_charset($in_charset, $out_charset, $v);
        }
    }
    else
    {
        $str_or_arr = iconv($in_charset, $out_charset, $str_or_arr);
    }
    return $str_or_arr;
}

/**
 * 实现fputcsv内置函数，将行格式化为 CSV 并写入文件指针
 *
 * fputcsv() 将一行（用 fields 数组传递）格式化为 CSV 格式并写入由 handle 指定的文件。返回写入字符串的长度，出错则返回 FALSE。
 * 可选的 delimiter 参数设定字段分界符（只允许一个字符）。默认为逗号：,。
 * 可选的 enclosure 参数设定字段字段环绕符（只允许一个字符）。默认为双引号："。
 *
 * @param resource $fp 存储文件指针
 * @param array $array 数据
 * @param string $delimiter 分界符
 * @param string $enclosure 环绕符
 * @return int
 */
if(!function_exists('fputcsv'))
{
    function fputcsv($fp, $array, $delimiter = ',', $enclosure = '"')
    {
        $data = $enclosure.implode($enclosure.$delimiter.$enclosure, $array).$enclosure."\n";
        return fwrite($fp, $data);
    }
}


/**
 * 产生一个随机字符串
 *
 * @param int $length	字符串长度
 * @param string $chars	随机字符范围
 * @return string
 */
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++)
    {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

/**
 * 返回文件扩展名
 *
 * @param string $filename 文件路径
 * @return string
 */
function fileext($filename)
{
    if(strpos($filename, '?'))
    {
        $filename = substr($filename, 0, strpos($filename, '?'));
    }
    return pathinfo($filename, PATHINFO_EXTENSION);
}

/**
 * 获取视频代码所使用的播放器
 * -- 返回 video,player,playerurl 组成的数组
 *
 * @param string $video
 * @return array|string
 */
function getVideoPlayer($video='')
{
    if(!$video) return '';
    $r['video'] = $video;
    $fileext = fileext($r['video']);
    if(preg_match('/^\[([a-zA-Z0-9]+)\]([^\[]+)(\[\/\1\])$/i', $r['video'], $matches))
    {
        $r['video'] = $matches[2];
        $r['player'] = $matches[1];
        $r['playerurl'] = '';
        if($r['player'] == 'ctvideo')
        {
            $new_setting = new setting();
            $video_setting = $new_setting->get('video');
            $r['playerurl'] = $video_setting['player'];
            unset($new_setting, $video_setting);
        }
    }
    elseif(!(stripos($r['video'], 'rtmp://') === false))
    {
        $r['player'] = 'rtmp';
    }
    elseif($fileext && preg_match('/imgcache.qq.com/',$r['video'],$matches) && preg_match('/TPout\.swf/',$r['video'],$matches))
    {
        $url = preg_replace('/\&amp;/','&',$r['video']);
        preg_match('/\&vid=([a-zA-Z0-9_]*)[\& ]/U',$url,$matches);
        $r['player_param_vid'] = $matches[1];
        $r['player'] = 'qq';
    }
    elseif($fileext && strlen($fileext)<7)
    {
        $r['player'] = $fileext;
    }
    else
    {
        $r['player'] = 'flash';
    }
    return $r;
}

/**
 * 将数组转换为字符串
 *
 * @param mixed $array  待转化数组
 * @param string $s		分隔符
 * @return string
 */
function implode_ids($array, $s = ',')
{
    if(empty($array)) return '';
    return is_array($array) ? implode($s, $array) : $array;
}

/**
 * 单词统计
 *
 * @param string $string	待统计文本
 * @param string $charset	字符集
 * @return int
 */
function words_count($string, $charset = 'utf-8')
{
    $string = strip_tags($string);
    $en_count = preg_match_all("/([[:alnum:]]|[[:punct:]])+/", $string, $matches);
    $string = preg_replace("/([[:alnum:]]|[[:space:]]|[[:punct:]])+/", '', $string);
    $zh_count = mb_strlen($string, $charset);
    $count = $en_count + $zh_count;
    return $count;
}

/**
 * 格式化存储单位
 *
 * @param int $size
 * @param bool $point 是否要小数
 * @return string
 */

function size_format($size, $point = true)
{
    $decimals = 0;
    $suffix = '';
    switch (true)
    {
        case $size >= 1073741824:
            $decimals = 2;
            $size = round($size / 1073741824 * 100) / 100;
            $suffix = 'GB';
            break;
        case $size >= 1048576:
            $decimals = 2;
            $size = round($size / 1048576 * 100) / 100;
            $suffix = 'MB';
            break;
        case $size >= 1024:
            $decimals = 2;
            $size = round($size / 1024 * 100) / 100;
            $suffix = 'KB';
            break;
        default:
            $decimals = 0;
            $suffix = 'B';
    }
    return number_format($size, $point ? $decimals : 0) . $suffix;
}

/**
 * 计算指定存储单位字符串的数值
 *
 * @param $size_string 存储单位字符串，如 128KB,1MB,1T,1GB 等
 * @return int 以 byte 计算的容量数值
 */
function size_calculate($size_string)
{
    if (is_int($size_string))
    {
        return $size_string;
    }
    $units = array('K', 'M', 'G', 'T', 'P', 'E');
    if (! preg_match('/^(\d+)([' . implode('', $units) . '])?(B)?$/i', $size_string, $matches))
    {
        return intval($size_string);
    }
    $value = intval($matches[1]);
    if (isset($matches[2]) && $matches[2])
    {
        $index = array_search(strtoupper($matches[2]), $units);
        if ($index !== false)
        {
            return $value * pow(1024, $index + 1);
        }
    }
    return $value;
}

/**
 *	截取字符串
 *
 * @param string $string	待截取字符串
 * @param int $length		截取长度，每个字符为一个长度，无论中英文
 * @param string $charset	字符字符集
 * @param string $etc		省略符
 * @return string
 */
function str_cutword($string, $length = 80, $charset = "utf-8", $etc = '...')
{
    $start = 0;
    if (! $length) return $string;
    if (function_exists('mb_substr'))
    {
        $slice = mb_substr($string, $start, $length, $charset);
    }
    else
    {
        $re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $string, $match);
        $slice = join('', array_slice($match [0], $start, $length));
    }
    if ($slice == $string)
    {
        return $slice;
    }
    return $slice . $etc;
}

/**
 * 友好格式化日期：已过去多久
 *
 * @param int $time 输入时间戳
 * @param string $format 时间格式
 * @param boolon $second 是否精确到秒
 * @return string
 */
function time_format($time, $format = 'Y年n月j日 G:i:s', $second = false)
{
    $diff = TIME - $time;
    if ($diff < 60 && $second)
    {
        return $diff ? $diff.'秒前' : '刚刚';
    }
    $diff = ceil($diff/60);
    if ($diff < 60)
    {
        return $diff  ? $diff.'分钟前' : '刚刚';
    }
    $d = date('Y,n,j', TIME);
    list($year, $month, $day) = explode(',', $d);
    $today = mktime(0, 0, 0, $month, $day, $year);
    $diff = ($time-$today) / 86400;
    switch (true)
    {
        case $diff < -2:
            break;
        case $diff < -1:
            $format = '前天 '.($second ? 'G:i:s' : 'G:i');
            break;
        case $diff < 0:
            $format = '昨天 '.($second ? 'G:i:s' : 'G:i');
            break;
        default:
            $format = '今天 '.($second ? 'G:i:s' : 'G:i');
    }
    return date($format, $time);
}

/**
 * 友好格式化日期：多久之后
 *
 * @param int $time 时间戳
 * @param string $full_format 超出指定天数范围后使用的时间戳
 * @param int $day_max 指定一个天数范围，当剩余天数大于该天数时，返回 $full_format 格式的时间
 * @return string 格式化结果
 */
function time_format_after($time, $full_format = 'Y-m-d H:i:s', $day_max = 30)
{
    $diff = $time - TIME;
    if ($diff == 0) {
        return '现在';
    }
    if ($diff < 0)
    {
        return time_format($time, $full_format, true);
    }
    if ($diff < 60) {
        return $diff . '秒后';
    }
    $minute = ceil($diff / 60);
    if ($minute < 60) {
        return $minute . '分钟后';
    }
    $day = ceil($diff / 86400);
    if ($day_max && $day > $day_max) {
        return date($full_format, $time);
    }
    $time = date('G:i', $time);
    if ($day < 1) {
        return '今天 ' . $time;
    }
    if ($day < 2) {
        return '明天 ' . $time;
    }
    if ($day < 3) {
        return '后天 ' . $time;
    }
    return $day . '天后';
}

/**
 * 友好格式化时时：将转换为时分秒显示
 *
 * @param int $second 秒数
 * @return string
 */
function second_format($second)
{
    $hour = $minute = 0;
    $str = '';
    if($second > 3600)
    {
        $hour = floor($second / 3600);
        $second = $second % 3600;
    }
    if($second > 60)
    {
        $minute = floor($second / 60);
        $second = $second % 60;
    }
    if($hour)
    {
        $str .= $hour ."小时";
    }
    if($minute)
    {
        $str .= $minute ."分";
    }
    if($second)
    {
        $str .= $second ."秒";
    }
    return $str;
}

/**
 * 截取字符串
 *
 * @param string $string 原始字符串
 * @param int $length 截取长度
 * @param string $dot 省略符
 * @param string $charset 字符集
 * @return string
 */
function str_cut($string, $length, $dot = '...', $charset = 'utf-8')
{
    $strlen = strlen($string);
    if($strlen <= $length) return $string;
    $specialchars = array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;');
    $entities = array('&', '"', "'", '<', '>');
    $string = str_replace($specialchars, $entities, $string);
    $strcut = '';
    if(strtolower($charset) == 'utf-8')
    {
        $n = $tn = $noc = 0;
        while($n < $strlen)
        {
            $t = ord($string[$n]);
            if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1; $n++; $noc++;
            } elseif(194 <= $t && $t <= 223) {
                $tn = 2; $n += 2; $noc += 2;
            } elseif(224 <= $t && $t < 239) {
                $tn = 3; $n += 3; $noc += 2;
            } elseif(240 <= $t && $t <= 247) {
                $tn = 4; $n += 4; $noc += 2;
            } elseif(248 <= $t && $t <= 251) {
                $tn = 5; $n += 5; $noc += 2;
            } elseif($t == 252 || $t == 253) {
                $tn = 6; $n += 6; $noc += 2;
            } elseif(bin2hex($string[$n]) >=65281||bin2hex($string[$n])<=65374){
                $tn = 3; $n += 3; $noc += 2;
            } else{
                $n++;
            }
            if($noc >= $length) break;
        }
        if($noc > $length) $n -= $tn;
        $strcut = substr($string, 0, $n);
    }
    else
    {
        $dotlen = strlen($dot);
        $maxi = $length - $dotlen - 1;
        for($i = 0; $i < $maxi; $i++)
        {
            $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
        }
    }
    if(strlen($strcut) == $strlen)
        return $string;
    else
        return $strcut.$dot;
}

/**
 * 截取字符串
 * 忽略对html标签,智能计算其中的字符长度,目前只支持计算p分隔的html文本，其他的需要再计算。
 * return array(
'status' => false, ture, 0 ,   false, 无法处理， 0 无需截取 ， 1 截取成功
 *
 * )
 */

function html_cut($string, $length, $charset = 'utf-8') {
    //计算每个p的值。
    if (!strpos($string,'</p>')) {
        //该篇文章无法计算长度。
        //return str_cut($string, $length, $dot, $charset );
        return array(
            'status' => false,
            'str' =>$string
        );
    } else {
        //将文章分隔成一个个p。来进行计算。
        if (preg_match_all('%<p[^>]*>(.*?)</p>%sm', $string, $matches)) {
            $result = '';
            $count = $words = 0;
            $status = 0;
            foreach($matches[0] as $k => $v) {
                if (substr_count($v,'<p') > 1) {
                    //暂时不处理嵌套p的情况
                    $result = $string;
                    break;
                } else {
                    $words = mb_strlen($matches[1][$k], $charset);
                }
                $count += $words;
                $result .= $v;
                if ($count > $length) {
                    if ($k != count($matches[0])-1) {
                        $status = true; //截取成功
                    }
                    break;
                }
            }
            if ($count <= $length) {
                //避免不止有p的情况。
                $result = $string;
            }
            return array(
                'status' => $status,
                'str' => $result
            );
        } else {
            //无法计算
            return array(
                'status' => false,
                'str' =>$string
            );
        }
    }
}

function origImg($img){
    $path_arr = explode('/',$img);
    $img_path = array_pop($path_arr);
    $img_arr  = explode('_',$img_path);
    if($img_arr['0'] != 'orig'){
        $img_path = 'orig_'.$img_path;
    }
    $path = join('/',$path_arr).'/'.$img_path;
    if(file_get_contents($path,0,null,0,1)){
        $img = $path;
    }
    return $img;
}


/**
 * 数据格式化解码，自动检测是JSON编码还是序列化编码
 *
 * @param string $data
 * @return string
 */
function decodeData($data)
{
    return is_array($data)
        ? $data
        : ($data[0]=='{' || $data[0]=='[') ? json_decode($data, true) : unserialize($data);
}

/**
 * 字符串编码（escape）
 *
 * @param string $str 待编码字符串
 * @param string $charset 字符集
 * @return string
 */
function escape($str, $charset = 'utf-8')
{
    preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/", $str, $r);
    $ar = $r[0];
    foreach($ar as $k=>$v)
    {
        $ar[$k] = ord($v[0]) < 128 ? rawurlencode($v) : '%u'.bin2hex(iconv($charset, 'UCS-2', $v));
    }
    return join('', $ar);
}

/**
 * 字符串解码（unescape）
 *
 * @param string $str 待解码字符串
 * @param string $charset 字符集
 * @return string
 */
function unescape($str, $charset = 'utf-8')
{
    $str = rawurldecode($str);
    $str = preg_replace("/\%u([0-9A-Z]{4})/es", "iconv('UCS-2', '$charset', pack('H4', '$1'))", $str);
    return $str;
}

/**
 * 路径格式化
 *
 * @param string $dir
 * @return string
 */
function format_dir($dir)
{
    return rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}

/**
 * url格式化
 *
 * @param string $url
 * @return string
 */
function format_url($url)
{
    return str_replace("\\", "/", $url);
}

/**
 * 向浏览器输出内容,格式化标准HTTP头
 *
 * @param string $data
 * @return strign
 */
function output($data)
{
    $strlen = strlen($data);
    if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && $strlen > 255 && extension_loaded('zlib') && !ini_get('zlib.output_compression') && ini_get('output_handler') != 'ob_gzhandler')
    {
        $data = gzencode($data, 4);
        $strlen = strlen($data);
        header('Content-Encoding: gzip');
        header('Vary: Accept-Encoding');
    }
    header('X-Powered-By: CMSTOP/1.0.0');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    header('ETag: "'.$strlen.'-'.time().'"');
    header('Accept-Ranges: bytes');
    return $data;
}

/**
 * 生成带参数的URL
 *
 * @param string $url 基础url
 * @param array $query 参数
 * @param bool $mode 是否转义
 * @return string
 */
function url_query($url, $query = array(), $mode = false)
{
    if ($query)
    {
        $data = parse_url($url);
        if (!$data) return false;
        if (isset($data['query']))
        {
            parse_str($data['query'], $q);
            $query = array_merge($q, $query);
        }
        $data['query'] = http_build_query($query);
        $url = http_build_url($data, $mode);
    }
    return $url;
}

/**
 * 分页函数
 *
 * @param int $total 总条目
 * @param int $page	当前页码
 * @param int $pagesize 每页条数
 * @param int $offset 页码显示数量控制（n*2+1）
 * @param string $url 基础URL
 * @param bool $mode 是否转义
 * @param string $tag 页码标签
 * @return string
 */
function pages($total, $page = 1, $pagesize = 20, $offset = 2, $url = null, $mode = false, $tag='li')
{
    if($total <= $pagesize) return '';
    $page = max(intval($page), 1);
    $pages = ceil($total/$pagesize);
    $page = min($pages, $page);
    $prepage = max($page-1, 1);
    $nextpage = min($page+1, $pages);
    $from = max($page - $offset, 2);
    if ($pages - $page - $offset < 1) $from = max($pages - $offset*2 - 1, 2);
    $to = min($page + $offset, $pages-1);
    if ($page - $offset < 2) $to = min($offset*2+2, $pages-1);
    $more = 1;
    if ($pages <= ($offset*2+5))
    {
        $from = 2;
        $to = $pages - 1;
        $more = 0;
    }
    $p_start_tag = '<'.$tag.'>';
    $p_end_tag = '</'.$tag.'>';
    $str = '';
    if ($page <= 1)
    {
        $str .= $p_start_tag.'<a href="javascript:void(0);" class="prev disable">上一页</a>'.$p_end_tag;
    }
    else
    {
        $str .= $p_start_tag.'<a href="'.pages_url($url, $prepage, $mode).'" class="prev">上一页</a>'.$p_end_tag;
    }
    $str .= $page == 1 ? $p_start_tag.'<a href="javascript:void(0);" class="now">1</a>'.$p_end_tag : $p_start_tag.'<a href="'.pages_url($url, 1, $mode).'">1'.($from > 2 && $more ? ' ...' : '').'</a>'.$p_end_tag;
    if ($to >= $from)
    {
        for($i = $from; $i <= $to; $i++)
        {
            $str .= $i == $page ? $p_start_tag.'<a href="javascript:void(0);" class="now">'.$i.'</a>'.$p_end_tag : $p_start_tag.'<a href="'.pages_url($url, $i, $mode).'">'.$i.'</a>'.$p_end_tag;
        }
    }
    $str .= $page == $pages ? $p_start_tag.'<a href="javascript:void(0);" class="now">'.$pages.'</a>'.$p_end_tag : $p_start_tag.'<a href="'.pages_url($url, $pages, $mode).'">'.($to < $pages-1 && $more ? '... ' : '').$pages.'</a>'.$p_end_tag;
    if ($page >= $pages)
    {
        $str .= $p_start_tag.'<a href="javascript:void(0);" class="next disable">下一页</a>'.$p_end_tag;
    }
    else
    {
        $str .= $p_start_tag.'<a href="'.pages_url($url, $nextpage, $mode).'" class="next">下一页</a>'.$p_end_tag;
    }
    return $str;
}

/**
 * 利用curl模拟浏览器发送请求
 *
 * @param string $url 请求的URL
 * @param array|string $post post数据
 * @param int $timeout 执行超时时间
 * @param boolean $sendcookie 是否发送当前cookie
 * @return array
 */
function request($url, $post = null, $timeout = 40, $sendcookie = true, $options = array())
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 35);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : 40);
    if ($sendcookie) {
        $cookie = '';
        foreach ($_COOKIE as $key=>$val)
        {
            $cookie .= rawurlencode($key).'='.rawurlencode($val).';';
        }
        curl_setopt($ch, CURLOPT_COOKIE , $cookie);
    }
    if ($post)
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($post) ? http_build_query($post) : $post);
    }

    if (!ini_get('safe_mode') && ini_get('open_basedir') == '')
    {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1 );
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    foreach ($options as $key=>$value)
    {
        curl_setopt($ch, $key, $value);
    }

    $ret = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $content_length = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    if (!$content_length) $content_length = curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
    $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    //增加错误信息。
    $error = '';
    if (empty($httpcode)) {
        $error = curl_error($ch);
        $errorno = curl_errno($ch);
    }
    curl_close($ch);
    return array(
        'httpcode'=>$httpcode,
        'content_length'=>$content_length,
        'content_type'=>$content_type,
        'content'=>$ret,
        'error' => $error,
        'errorno' => $errorno,
    );
}


/**
 * 仅执行第一次匹配替换
 * @param string $search 查找的字符串
 * @param string $replace 执行替换的字符串
 * @param string $subject 原字符串
 * @return string
 */
function str_replace_once($search, $replace, $subject)
{
    $pos = strpos($subject, $search);
    if ($pos === false)
    {
        return $subject;
    }
    return substr_replace($subject, $replace, $pos, strlen($search));
}

/**
 * 移除内容开始的 BOM 信息
 *
 * @param $content 要移除 BOM 头的内容
 * @return string 被移除 BOM 头后的内容
 */
function remove_bom($content)
{
    if ($content && substr($content, 0, 3) == chr(239).chr(187).chr(191))
    {
        $content = substr($content, 3);
    }
    return $content;
}

/**
 * 计算$url的绝对地址
 *
 * @param $url
 * @param $baseurl
 *
 * @return string
 */
function absoluteurl($url, $baseurl)
{
    $url = trim($url);
    if ($url == '' || $url == '#') {
        return $url;
    }

    $url = explode('?', $url, 2);
    $query = isset($url[1]) ? "?$url[1]" : '';
    $url = $url[0];

    if ($baseurl && !preg_match('#^(?:[a-z]{3,10}):#i', $url)) {
        $uri = parse_url($baseurl);
        $pass = isset($uri['pass']) ? ":{$uri['pass']}" : '';
        $user = isset($uri['user']) ? "{$uri['user']}{$pass}@" : '';
        $host = $uri['host'];
        $scheme = $uri['scheme'];
        if (isset($uri['port']) && !(($scheme == 'http' && $uri['port'] == 80) || ($scheme == 'https' && $uri['port'] == 443)))
        {
            $host .= ':' . $uri['port'];
        }
        $httphost = "{$scheme}://{$user}{$host}";
        if ($url[0] == '/') {
            $url = $httphost . $url;
        } else {
            $path = explode('/', $uri['path']);
            if (strlen($url)) {
                $path[count($path)-1] = $url;
            }
            $url = $httphost . implode('/', $path);
        }
    }

    while (strpos($url, './') !== false) {
        $old = $url;
        $url = preg_replace('#([^/]+/)(\.{2}/)#e', '"$1"=="$2"?"$1$2":""', $url);
        $url = str_replace('/./', '/', $url);
        if ($url == $old) break;
    }
    return $url . $query;
}

/**
 * 以自然方式截取字符串

 *
 * @param $string
 * @param $length
 * @param string $dot
 * @return mixed|string
 */
function str_natcut($string, $length, $dot = '...')
{
    if (!$string || !$length) return $string;
    $string = htmlspecialchars_decode($string);
    $string = preg_replace('/\s{2,}/', ' ', $string);
    $maxlen = min($length, mb_strlen($string, 'UTF-8'));
    $chars = preg_split('/([\xF0-\xF7][\x80-\xBF]{3}|[\xE0-\xEF][\x80-\xBF]{2}|[\xC0-\xDF][\x80-\xBF]|[\x00-\x7F])/m', $string, $maxlen + 1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    $index = 0;
    $length = .0;
    $total = count($chars);
    $result = array();
    while ($length < $maxlen && $index < $total)
    {
        $char = $chars[$index];
        if (preg_match('/[\xE0-\xEF][\x80-\xBF]{2}/', $char))
        {
            if (($maxlen - $length) < 1) break;
            $length += 1;
        }
        else
        {
            $length += 0.5;
        }
        $result[] = $char;
        $index++;
    }
    $result = implode('', $result);
    unset($chars, $char);
    return htmlspecialchars($result) . ($result == $string ? '' : $dot);
}



/**
 * 以自然的方式计算字符串长度
 *
 * 一个汉字计算一个长度，两个英文计算一个长度
 *
 * @param $string
 * @return float|int
 */
function str_natcount($string)
{
    $length = 0;
    if (!$string) return $length;
    $string = preg_replace('/[\xE0-\xEF][\x80-\xBF]{2}/m', '__', $string);
    return ceil(mb_strlen($string, 'UTF-8') / 2);
}

/**
 * 将上传文件的路径转成绝对路径
 *
 * @param $url
 * @param string $default
 * @param string $remote
 * @return string
 */
function abs_uploadurl($url, $default = '', $remote = false)
{
    if(!$url) return $default;
    if(strpos($url, '://') === false)
    {
        return ($remote ? REMOTE_URL : UPLOAD_URL) . $url;
    }
    return $url;
}

function script_template($html)
{
    return $html ? str_replace(array('&', '</textarea'), array('&amp;', '&lt;/textarea'), $html) : $html;
}

/**
 * 用于escape编码的解码
 *
 * @param $str
 * @param string $charset
 * @return string
 */
function urldecode_escape($str, $charset='UTF-8')
{
    $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
    return html_entity_decode($str,null,'UTF-8');
}


/**
 * 检测并将 GBK 编码的文本转换为 UTF-8 编码
 *
 * @param $string 要转换的文本
 * @return mixed 转换之后的文本
 */
function gbk_to_utf8($string)
{
    $encoded = json_encode($string);
    if ($encoded == 'null' && $string != 'null')
    {
        return str_charset('gbk', 'utf-8', $string);
    }
    return $string;
}

/**
 * 将秒数转换为时间字符串
 *
 * 如：
 * 10 将转换为 00:10，
 * 120 将转换为 02:00，
 * 3601 将转换为 01:00:01
 *
 * @param $second 秒数
 * @return string 时间字符串
 */
function second_to_time($second)
{
    $second = intval($second);
    if (!$second) return '';

    $hours = floor($second / 3600);
    $hours = $hours ? str_pad($hours, 2, '0', STR_PAD_LEFT) : 0;
    $second = $second % 3600;
    $minutes = floor($second / 60);
    $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
    $seconds = $second % 60;
    $seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);

    return implode(':', $hours ? compact('hours', 'minutes', 'seconds') : compact('minutes', 'seconds'));
}

/**
 * 为内容中的关键词添加链接
 *
 * @param string $content 内容
 * @param string $keyword 关键词
 * @param string $link 链接
 * @param bool $once 是否只替换一次
 * @return string 替换后的结果
 */
function keyword_add_link($content, $keyword, $link, $once = true)
{
    if (stripos($content, $keyword) === false)
    {
        return $content;
    }

    $result = array();
    $pos_open = 0;
    $pos_close = 0;
    $replaced = false;

    $is_alnum = ctype_alnum($keyword);

    $parts = preg_split(
        '#(<[^>]+\/?>)#ms', $content, -1,
        PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE
    );
    foreach ($parts as $part)
    {
        if (($once && $replaced)
            || $part[0][0] == '<' && $part[0][strlen($part[0]) - 1] == '>'
            || stripos($part[0], $keyword) === false)
        {
            $result[] = $part[0];
            if (!$once || !$replaced)
            {
                if (strtolower(substr($part[0], 0, 3)) == '<a ')
                {
                    $pos_open = $part[1];
                }
                elseif (strtolower($part[0]) == '</a>')
                {
                    $pos_close = $part[1];
                }
            }
            continue;
        }
        if ($pos_open && $pos_open > $pos_close)
        {
            $result[] = $part[0];
            continue;
        }
        if ($is_alnum)
        {
            $result[] = preg_replace(
                '/([^a-zA-Z0-9])('.preg_quote($keyword).')([^a-zA-Z0-9])/i',
                '\1<a href="'.$link.'" target="_blank">\2</a>\3',
                $part[0],
                $once ? 1 : -1
            );
            if ($part[0] == $result[count($result)-1])
            {
                continue;
            }
        }
        else
        {
            $result[] = preg_replace(
                '/('.preg_quote($keyword).')/i',
                '<a href="'.$link.'" target="_blank">\1</a>',
                $part[0],
                $once ? 1 : -1
            );
        }
        $replaced = true;
    }
    return implode('', $result);
}

/**
 * 递归合并两个数组，array_merge_recursive 的覆盖版
 *
 * 如果输入的数组中有相同的字符串键名，则这些值会被合并到一个数组中去，这将递归下去，
 * 因此如果一个值本身是一个数组，本函数将按照相应的条目把它合并为另一个数组。
 * 然而，如果数组具有相同的数组键名，后一个值将 **会覆盖** 原来的值，而不是附加到后面。
 *
 * @param $arr1
 * @param $arr2
 * @return array
 * @from http://php.net/manual/en/function.array-merge-recursive.php#42663
 */
function array_merge_recursive_replace($arr1, $arr2)
{
    if (!is_array($arr1) || !is_array($arr2)) {
        return $arr2;
    }
    foreach ($arr2 as $key => $value) {
        $arr1[$key] = array_merge_recursive_replace($arr1[$key], $value);
    }
    return $arr1;
}

/**
 * 二维数组按指定字段索引
 *
 * @param $array
 * @param $key
 * @return array
 */
function sort_array($array, $key)
{
    $result = array();
    foreach ($array as $item)
    {
        if (empty($item[$key]))
        {
            continue;
        }
        $result[$item[$key]] = $item;
    }
    return $result;
}

/**
 * 将指定字符串转化为 32 位随机字符
 *
 * @param $input
 * @return string
 */
function str_short($input)
{
    $base32 = array(
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
        'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
        'y', 'z', '0', '1', '2', '3', '4', '5'
    );

    $hex = substr(md5($input), 8, 16);
    $hexLen = strlen($hex);
    $subHexLen = $hexLen / 8;
    $output = array();

    for ($i = 0; $i < $subHexLen; $i++) {
        $subHex = substr($hex, $i * 8, 8);
        $int = 0x3FFFFFFF & (1 * ('0x' . $subHex));
        $out = '';

        for ($j = 0; $j < 6; $j++) {
            $val = 0x0000001F & $int;
            $out .= $base32[$val];
            $int = $int >> 5;
        }

        $output[] = $out;
    }

    return implode('', $output);
}

/**
 * 将指定字符串转化为 32 位随机字符
 *
 * @param $color
 * @param $input type
 * @return string|array
 */
function format_color($color, $input_type = 'hex')
{
    if (($input_type == 'hex') && (strlen($color) == 7)) {
        $ret = array();
        $ret[] = hexdec(substr($color, 1, 2));
        $ret[] = hexdec(substr($color, 3, 2));
        $ret[] = hexdec(substr($color, 5, 2));
        return $ret;
    } elseif (($input_type == 'dec') && is_array($color)) {
        $ret = '#';
        $ret .= dechex($color[0]);
        $ret .= dechex($color[1]);
        $ret .= dechex($color[2]);
        return $ret;
    }
    return '';
}



//检测字符串 相当于js的indexof
function check_str($str, $substr)
{
    $nums=substr_count($str,$substr);
    if ($nums>=1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//通过时间戳 算天数，返回数组
function calculateDate($date,$end,$arr=[]){
    if($date<=$end){
        array_push($arr,date('Y-m-d',$date));
        $newdate = $date + 86400;
        calculateDate($newdate,$end,$arr);
        exit;
    }
    else{
        return $arr;
    }
}

//键值相同的数组合并
function keycombine($data,$key){
    $result = [];
    foreach ($data as $k=>$v){
        $result[$v[$key]][] = $v;
    }
    return $result;
}

//跨域
function cross(){
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept');
    header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');
}

function ui() {
    return new \ui\Component;
}

//0 进入 1.完成 2退出
//微信验签（用户后台接口校验）
function wx_sign($arr){
    $str = $arr;
    $open_key = $arr['open_key'];
    unset($str['sign']);
    unset($str['open_key']);
    foreach ($str as $k=>$v){
        $str[$k] = $k .'='. $v;
    }
    ksort($str);
    $str = join($str,'&');
    $str = $str . '&open_key=' . $open_key;
    $str = strtoupper(MD5($str));
    return $str;
}
//树型数据
function getTree($arr){
   //排序的目的就是防止这种情况造成的混乱
   uasort($arr,"cmd");
   //定义目标数组
    $d = array();
    //定义索引数组，用于记录节点在目标数组的位置
    $ind = array();
    foreach($arr as $v) {
        $v['child'] = array(); //给每个节点附加一个child项
        if($v['pid'] == 0) {
            $i = count($d);
            $d[$i] = $v;
            $ind[$v['id']] =& $d[$i];
        }else {
            $i = count($ind[$v['pid']]['child']);
            $ind[$v['pid']]['child'][$i] = $v;
            $ind[$v['id']] =& $ind[$v['pid']]['child'][$i];
        }
    }
    return $d;
}
//排序，为避免数据中父节点在子节点后面出现，这种情况在多次修改数据后经常会发生的
function cmd($a,$b) {
    if($a['pid']==$b['pid']) return 0;
    return $a['pid']>$b['pid']?1:-1;
}



//递归找父集
function getFather($alllist,$cate_id){
    $father=[];
    foreach ($alllist as $k=>$v){
        if($v['id']==$cate_id){
            $father[]=$v['id'];
            getFather($alllist,$v['pid']);
        }
    }
    return $father;
}
//递归找子集
function getSon($alllist,$cate_id){
    $child=[];
    foreach($alllist as $k=>$v){
        if($cate_id==$v['pid']){
            $child[] = $v;
            getSon($alllist,$v['id']);
        }
    }
    return $child;
}

//图片转base64图
function base64_image($image_file){
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

/**
 * 发送邮件验证码
 * @param string $title 邮件标题
 * @param string $content 邮件内容
 * @param string $FromName 信件人姓名
 * @param string $to 邮件地址
 * @return json 成功|失败
 */
//
function send_email($title,$content,$FromName,$to){
    $mail = new PHPMailer();
    $mail->isSMTP();
    $mail->CharSet = 'utf-8';
    $mail ->Host = 'smtp.qq.com';
    $mail -> SMTPSecure = 'ssl';
    $mail ->SMTPAuth =true;
    $mail -> Username = '2729385524@qq.com';
    $mail -> Password = 'vakgcsqljtvgdegi';
    $mail->From = '2729385524@qq.com';
    $mail->isHTML(true);
    $mail -> Port = 465;
    $mail->FromName = $FromName;//信件人姓名
    $mail ->addAddress($to);
    $mail -> Subject = $title;
    $mail -> Body = $content ;//双引号里的变量可自动解析
    //  $mail -> addReplyTo('2729385524@qq.com','回复内容');
    if(!$mail->send()){
        return_msg(1,'发送失败！');
    }
    else{
        return_msg(0,'发送成功!');
    }
}

//生成随机数(生成位数)
function make_code($num){
    $max=pow(10,$num)-1;
    $min=pow(10,($num -1));
    return rand($min,$max);
}

function make_code1(){
    return md5(microtime() . rand(100000, 999999));
}

//arr转json
function encode($data){
    return json_encode($data,JSON_UNESCAPED_UNICODE);
}
//arr转json 包含tag
function tag_encode($data){
    return json_encode($data,\JSON_HEX_TAG);
}
//json转arr
function decode($data){
    return json_decode($data,true);
}

function obj_decode($data){
    return json_decode($data->getContent(),true);
}
//返回参数
function return_msg($code,$msg='',$data=[],$jump = ''){
    $return_data['code']=$code;
    $return_data['msg']=$msg;
    $return_data['data']=$data;
    $return_data['jump'] = $jump;
    exit( encode($return_data) );
}

function http_ajax($url, $data = null) {
    if (!is_null($data) && is_array($data)) {
        $url .= '?' . http_build_query($data);
    } elseif (!is_null($data) && is_string($data)) {
        $url .= '?' . $data;
    }
    $header = [
        'X-Requested-With:XMLHttpRequest', // 设置ajax请求头
    ];
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_TIMEOUT, 1);
    curl_setopt($oCurl, CURLOPT_TIMEOUT_MS, 1100);
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}


function http_get($url, $data = null) {
    if (!is_null($data) && is_array($data)) {
        $url .= '?' . http_build_query($data);
    } elseif (!is_null($data) && is_string($data)) {
        $url .= '?' . $data;
    }
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_TIMEOUT, 1);
    curl_setopt($oCurl, CURLOPT_TIMEOUT_MS, 1100);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

function http_post($url, $post_data) {
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, 1);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $post_data);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

function http_put($url, $data) {
    $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, "PUT"); //设置请求方式
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($oCurl, CURLOPT_POST, 1);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $data);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

function http_delete($url, $data) {
    $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, "DELETE"); //设置请求方式
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, 1);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $data);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * 转ID
 * @param type $str
 * @return type
 */
function url_encode_id($str) {
    $str = urlencode($str);
    $str = str_replace('%', '_', $str);
    return $str;
}


/*
 * 下划线转驼峰
 */

function convert_underline($str) {
    $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function($matches) {
        return strtoupper($matches[2]);
    }, $str);
    return $str;
}

/*
 * 驼峰转下划线
 */
function hump_to_line($string) {
    $string = preg_replace_callback('/([A-Z]{1})/', function($matches) {
        return '_' . strtolower($matches[0]);
    }, $string);
    if (substr($string, 0, 1) === '_') {
        $string = substr($string, 1);
    }
    return $string;
}


function to_date($format, $datetime) {
    $unixtime = strtotime($datetime);
    return date($format, $unixtime);
}


/**
 * 验证手机格式是否合法
 * @param type $mobile 移动号码
 * @return type bool
 */
function is_mobile_check($mobile) {
    preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile, $matches);
    return (count($matches) != 0);
}

/**
 * 验证IOS IDFA是否合法
 * @param type $code
 * @return type
 */
function is_ios_idfa($value) {
    preg_match('/^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}$/', $value, $matches);
    return (count($matches) != 0);
}


function rm_wrap($subject){
    return str_replace(["\r", '\n'], '', $subject);
}

